//
//  CustomCordovaPlugin.m
//  FuncFanc
//
//  Created by careate-hubing on 2021/9/13.
//  Copyright © 2021 huhu. All rights reserved.
//

#import "CustomCordovaPlugin.h"
#import "SDWebImageDownloader.h"

@implementation CustomCordovaPlugin


-(void)getImageBase64ByCommend:(CDVInvokedUrlCommand*)command
{
    __weak typeof(self) ws = self;
    self.getImageBase64ByCommendID = command.callbackId;
    NSDictionary *param = command.arguments.firstObject;
    DoctorPhotoModel *model = [DoctorPhotoModel modelWithDictionary:param];
    LKDBHelper *helper = [LKDBHelper getUsingLKDBHelper];
    NSDictionary *whereDic = @{@"doctorCID":model.doctorCID?:@"",@"MD5Str":model.MD5Str?:@""};
    [helper search:[DoctorPhotoModel class] where:whereDic orderBy:nil offset:0 count:INTMAX_MAX callback:^(NSMutableArray * _Nullable array) {
        if (array.count > 0)
        {
            DoctorPhotoModel *model1 = array.firstObject;
            //返回图片base64
            NSDictionary *param = @{@"imageUrl":model1.photoBase64?:@""};
            NSString *jsonStr = [QHCommonTool dictionaryTOjsonString:param];
            CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:jsonStr];
            [ws.commandDelegate sendPluginResult:pluginResult callbackId:ws.getImageBase64ByCommendID];
        }
        else
        {
            //下载。返回  存储base64
            [[SDWebImageDownloader sharedDownloader]downloadImageWithURL:[NSURL URLWithString:model.photoUrl] completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
                if (!error) {
                    NSString *imageBase64 = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
                    NSDictionary *param = @{@"imageUrl":imageBase64};
                    NSString *jsonStr = [QHCommonTool dictionaryTOjsonString:param];
                    CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:jsonStr];
                    [ws.commandDelegate sendPluginResult:pluginResult callbackId:ws.getImageBase64ByCommendID];
                    model.photoBase64 = imageBase64;
                    model.MD5Str = [imageBase64 md5];
                    [helper insertWhenNotExists:model];
                }
            }];
        }
    }];
}


@end
